package com.jit.app.util;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class InstalledApplicationUtils {

    public static List<PackageInfo> getAllInstalledApplications(Context context){

        PackageManager manager = context.getPackageManager();
        List<PackageInfo> installedPackages = manager.getInstalledPackages(0);
        List<PackageInfo> installedPackages2 = new ArrayList<>();
        for(PackageInfo packageInfo : installedPackages){
            if((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)==0){
                installedPackages2.add(packageInfo);
            }

        }
        return installedPackages2;
    }

    public static List<String> getAllInstalledAppPackageName(Context context){
        List<PackageInfo> list = getAllInstalledApplications(context);
        List<String> packs = new ArrayList<>();
        for(PackageInfo packageInfo : list){
            packs.add(packageInfo.packageName);
        }
        return packs;
    }


    public static boolean isInstalled(String pack, Context context){
        boolean result = false;
        List<PackageInfo> allInstalledApplications = getAllInstalledApplications(context);
        for (PackageInfo packageInfo:allInstalledApplications){
            if(pack.equals(packageInfo.packageName)){
                result = true;
                break;
            }
        }
        return result;
    }


    public static List<JSONObject> getNewVersionAppList(Context context, List<JSONObject> newestAppList){
        List<PackageInfo> allInstalledApplications = getAllInstalledApplications(context);
        List<JSONObject> resultList = new ArrayList<>();
        for(JSONObject jsonObject : newestAppList){
            for(PackageInfo info : allInstalledApplications){
                if(jsonObject.getString("versionNo").compareToIgnoreCase(info.versionName) > 0){
                    resultList.add(jsonObject);
                    break;
                }
            }
        }

        return resultList;
    }
}
